package cn.wowjoy.office.common.widget.album.selector;

import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.app.AlertDialog;
import android.arch.lifecycle.Observer;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.SimpleItemAnimator;
import android.view.KeyEvent;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.inject.Inject;

import cn.wowjoy.office.BuildConfig;
import cn.wowjoy.office.R;

import cn.wowjoy.office.baselivedata.appbase.NewBaseActivity;
import cn.wowjoy.office.common.customview.MaskFramLayout;
import cn.wowjoy.office.common.decoration.GridSpacesItemDecoration;
import cn.wowjoy.office.common.decoration.SimpleItemDecoration;
import cn.wowjoy.office.common.widget.MyToast;
import cn.wowjoy.office.common.widget.album.preview.PhotoPreviewActivity;
import cn.wowjoy.office.data.constant.Constants;
import cn.wowjoy.office.data.mock.Folder;
import cn.wowjoy.office.data.mock.Image;
import cn.wowjoy.office.data.mock.ImageModel;
import cn.wowjoy.office.databinding.ActivityImageSelectorBinding;
import cn.wowjoy.office.utils.ImageSelectorUtils;
import cn.wowjoy.office.utils.PermissionUtil;

@Route(path = "/common/widget/album/selector/ImageSelector")
public class ImageSelectorActivity extends NewBaseActivity<ActivityImageSelectorBinding,ImageSelectorViewModel> {

    private GridLayoutManager mLayoutManager;

    private ArrayList<Folder> mFolders;
    private Folder mFolder;
    private boolean isToSettings = false;
    private static final int PERMISSION_REQUEST_CODE = 0X00000011;
    private static final int REQUEST_CODE_CAMERA = 0X00000012;

    private boolean isSelected;
    private boolean isOpenFolder;
    private boolean isShowTime;
    private boolean isInitFolder;
    @Autowired
    boolean isSingle;
    @Autowired
    int mMaxCount;


    private int initHeight;


    /**
     * 启动图片选择器
     *
     * @param activity
     * @param requestCode
     * @param isSingle       是否单选
     * @param maxSelectCount 图片的最大选择数量，小于等于0时，不限数量，isSingle为false时才有用。
     */
    public static void openActivity(Activity activity, int requestCode,
                                    boolean isSingle, int maxSelectCount) {
        Intent intent = new Intent(activity, ImageSelectorActivity.class);
        intent.putExtra(Constants.MAX_SELECT_COUNT, maxSelectCount);
        intent.putExtra(Constants.IS_SINGLE, isSingle);
        activity.startActivityForResult(intent, requestCode);
    }





    @Override
    protected void init(Bundle savedInstanceState) {

        ARouter.getInstance().inject(this);
        binding.setViewModel(viewModel);
//        Intent intent = getIntent();
//        mMaxCount = intent.getIntExtra(Constants.MAX_SELECT_COUNT, 0);
//        isSingle = intent.getBooleanExtra(Constants.IS_SINGLE, false);
        initObsever();
        initListener();
        initImageList();
        checkPermissionAndLoadImages();
        hideFolderList();
        setSelectImageCount(0);
    }

    private void initObsever(){
        viewModel.getClick().observe(this, new Observer<ImageSelection>() {
            @Override
            public void onChanged(@Nullable ImageSelection imageSelection) {
                toPreviewActivity(imageSelection.getImages(),imageSelection.getPosition());
            }
        });
        viewModel.getFolderMediatorLiveData().observe(this, new Observer<Folder>() {
            @Override
            public void onChanged(@Nullable Folder folder) {
                setFolder(folder);
                closeFolder();
            }
        });
        viewModel.getSelectorCount().observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(@Nullable Integer integer) {
                setSelectImageCount(integer.intValue());
            }
        });
        viewModel.getTakephoto().observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(@Nullable Boolean aBoolean) {
                selectPictureViaTakingPhoto();
            }
        });
    }
    private void initListener(){
        binding.back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        binding.floder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.floder.setSelected(isOpenFolder);
                //展开收起目录
                if (isInitFolder) {
                    if (isOpenFolder) {
                        closeFolder();
                    } else {
                        openFolder();
                    }
                }
            }
        });

        binding.floderMask.setBgAlapht(128);
        binding.floderMask.setDimissListener(new MaskFramLayout.DimissListener() {
            @Override
            public void onDismiss() {
                binding.floder.setSelected(isOpenFolder);
                closeFolder();
            }
        });
        binding.complete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //选择完成返回结果
                confirm();

            }
        });

        binding.preview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转至预览页面
                ArrayList<Image> images = new ArrayList<>();
                images.addAll(viewModel.adapter.getSelectImages());
                toPreviewActivity(images, 0);
            }
        });
    }

    private void confirm() {
        if (viewModel.adapter == null) {
            return;
        }
        //因为图片的实体类是Image，而我们返回的是String数组，所以要进行转换。
        ArrayList<Image> selectImages = viewModel.adapter .getSelectImages();
        ArrayList<String> images = new ArrayList<>();
        for (Image image : selectImages) {
            images.add(image.getPath());
        }

        //点击确定，把选中的图片通过Intent传给上一个Activity。
        Intent intent = new Intent();
        intent.putStringArrayListExtra(ImageSelectorUtils.SELECT_RESULT, images);
        setResult(RESULT_OK, intent);

        finish();
    }

    @Override
    public void onBackPressed() {
        setResult(RESULT_CANCELED);
        super.onBackPressed();
    }

    /**
     * 初始化图片列表
     */
    private void initImageList() {
        // 判断屏幕方向
        Configuration configuration = getResources().getConfiguration();
        if (configuration.orientation == Configuration.ORIENTATION_PORTRAIT) {
            mLayoutManager = new GridLayoutManager(this, 3);
        } else {
            mLayoutManager = new GridLayoutManager(this, 5);
        }

        binding.albumRecyclerview.setLayoutManager(mLayoutManager);
        int space = getResources().getDimensionPixelSize(R.dimen.image_padding);
        binding.albumRecyclerview.addItemDecoration(new GridSpacesItemDecoration(space,true));
        viewModel.initAlbumAdapter(mMaxCount,isSingle);
        binding.albumRecyclerview.setAdapter(viewModel.adapter);
        ((SimpleItemAnimator) binding.albumRecyclerview.getItemAnimator()).setSupportsChangeAnimations(false);
        if (mFolders != null && !mFolders.isEmpty()) {
            setFolder(mFolders.get(0));
        }

    }
    /**
     * 检查权限并加载SD卡里的图片。
     */
    private void checkPermissionAndLoadImages() {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//            Toast.makeText(this, "没有图片", Toast.LENGTH_LONG).show();
            return;
        }
        List<String> group = new ArrayList<>();
        group.add(Manifest.permission_group.STORAGE);

        if (requestRuntimePermissions( PermissionUtil.permissionGroup(group,null),PERMISSION_REQUEST_CODE)){
            loadImageForSDCard();
        }
    }

    private File tempFile;
    private String filePath = BuildConfig.PICTURE_PATH;
    private void takePhoto(){
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (cameraIntent.resolveActivity(getPackageManager()) != null) {
            // 设置系统相机拍照后的输出路径
            // 创建临时文件
            tempFile = createTempFile(filePath);
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
            startActivityForResult(cameraIntent, Constants.TAKEpHOTO_CODE);
        } else {
            new MyToast(this).showinfo("没有可用的相机");
        }
    }

    private File createTempFile(String filePath) {
        String timeStamp = new SimpleDateFormat("MMddHHmmss", Locale.CHINA).format(new Date());
        String externalStorageState = Environment.getExternalStorageState();
        File dir = new File(Environment.getExternalStorageDirectory() + filePath);
        if (externalStorageState.equals(Environment.MEDIA_MOUNTED)) {
            if (!dir.exists()) {
                dir.mkdirs();
            }
            return new File(dir, timeStamp + ".png");
        } else {
            File cacheDir = getCacheDir();
            return new File(cacheDir, timeStamp + ".png");
        }
    }

    public void selectPictureViaTakingPhoto() {
        List<String> group = new ArrayList<>();
        group.add(Manifest.permission_group.CAMERA);

        if (requestRuntimePermissions( PermissionUtil.permissionGroup(group,null),REQUEST_CODE_CAMERA)){
            takePhoto();
        }


    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST_CODE:
                for (int gra : grantResults) {
                    if (gra != PackageManager.PERMISSION_GRANTED) {
                        //拒绝权限，弹出提示框。
                        showExceptionDialog();
                        return;
                    }
                }
                //允许权限，加载图片。
                loadImageForSDCard();
                break;
            case REQUEST_CODE_CAMERA:
                if (grantResults.length > 0) {
                    for (int gra : grantResults) {
                        if (gra != PackageManager.PERMISSION_GRANTED) {
                            return;
                        }
                    }
                }
               //
                takePhoto();
                break;

        }
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN && isOpenFolder) {
            closeFolder();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    @Override
    protected void onStart() {
        super.onStart();
        if (isToSettings) {
            isToSettings = false;
            checkPermissionAndLoadImages();
        }
    }

    /**
     * 处理图片预览页返回的结果
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case Constants.RESULT_CODE:
                if (data != null && data.getBooleanExtra(Constants.IS_CONFIRM, false)) {
                    //如果用户在预览页点击了确定，就直接把用户选中的图片返回给用户。
                    confirm();
                } else {
                    //否则，就刷新当前页面。
                    viewModel.adapter.notifyDataSetChanged();
                    setSelectImageCount( viewModel.adapter.getSelectImages().size());
                }
                break;
            case Constants.TAKEpHOTO_CODE:

                if (data == null){
                    ArrayList<String> images = new ArrayList<>();
                    images.add(tempFile.getAbsolutePath());
                    //点击确定，把选中的图片通过Intent传给上一个Activity。
                    Intent intent = new Intent();
                    intent.putStringArrayListExtra(ImageSelectorUtils.SELECT_RESULT, images);
                    setResult(RESULT_OK, intent);
                    finish();
                }
                break;
        }

    }

    /**
     * 横竖屏切换处理
     *
     * @param newConfig
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (mLayoutManager != null &&  viewModel.adapter != null) {
            //切换为竖屏
            if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
                mLayoutManager.setSpanCount(3);
            }
            //切换为横屏
            else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
                mLayoutManager.setSpanCount(5);
            }
            viewModel.adapter.notifyDataSetChanged();
        }
    }


    /**
     * 发生没有权限等异常时，显示一个提示dialog.
     */
    private void showExceptionDialog() {
        new AlertDialog.Builder(this)
                .setCancelable(false)
                .setTitle("提示")
                .setMessage("该相册需要赋予访问存储的权限，请到“设置”>“应用”>“权限”中配置权限。")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                        finish();
                    }
                }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
                startAppSettings();
                isToSettings = true;
            }
        }).show();
    }

    /**
     * 启动应用的设置
     */
    private void startAppSettings() {
        Intent intent = new Intent(
                Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);
    }
    /**
     * 刚开始的时候文件夹列表默认是隐藏的
     */
    private void hideFolderList() {
        binding.floderRecyclerview.post(new Runnable() {
            @Override
            public void run() {
                binding.floderRecyclerview.setTranslationY(binding.floderRecyclerview.getHeight());
                binding.floderRecyclerview.setVisibility(View.GONE);
                binding.floderMask.setVisibility(View.GONE);
            }
        });
    }

    /**
     * 从SDCard加载图片。
     */
    private void loadImageForSDCard() {
        ImageModel.loadImageForSDCard(this, new ImageModel.DataCallback() {
            @Override
            public void onSuccess(ArrayList<Folder> folders) {
                mFolders = folders;
                initHeight= getResources().getDimensionPixelSize(R.dimen.height)*folders.size();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (mFolders != null && !mFolders.isEmpty()) {
                            initFolderList();
                            setFolder(mFolders.get(0));
                        }
                    }
                });
            }
        });
    }
    /**
     * 初始化图片文件夹列表
     */
    private void initFolderList() {
        if (mFolders != null && !mFolders.isEmpty()) {
            isInitFolder = true;
            binding.floderRecyclerview.setLayoutManager(new LinearLayoutManager(this));
            binding.floderRecyclerview.addItemDecoration(new SimpleItemDecoration(this,SimpleItemDecoration.VERTICAL_LIST));
            viewModel.initFloder(mFolders);
            binding.floderRecyclerview.setAdapter(viewModel.floderAdapter);
        }
    }

    protected void setSelectImageCount(int count) {
        if (count == 0) {
            binding.complete.setEnabled(false);
            binding.preview.setEnabled(false);
            binding.complete.setText("确定");
            binding.preview.setText("预览");
        } else {
            binding.complete.setEnabled(true);
            binding.preview.setEnabled(true);
            binding.preview.setText("预览(" + count + ")");
            if (isSingle) {
                binding.complete.setText("确定");
            } else if (mMaxCount > 0) {
                binding.complete.setText("确定(" + count + "/" + mMaxCount + ")");
            } else {
                binding.complete.setText("确定(" + count + ")");
            }
        }
    }
    protected void toPreviewActivity(ArrayList<Image> images, int position) {
        if (images != null && !images.isEmpty()) {
            PhotoPreviewActivity.openActivity(this, images,
                    viewModel.adapter.getSelectImages(), isSingle, mMaxCount, position);
        }
    }
    /**
     * 设置选中的文件夹，同时刷新图片列表
     *
     * @param folder
     */
    protected void setFolder(Folder folder) {
        if (folder != null && viewModel.adapter != null && !folder.equals(mFolder)) {
            mFolder = folder;
            binding.floder.setText(folder.getName());
            binding.albumRecyclerview.scrollToPosition(0);
            viewModel.adapter.refresh(folder.getImages());
        }
    }
    /**
     * 弹出文件夹列表
     */
    private void openFolder() {
        if (!isOpenFolder) {
            binding.floderMask.setVisibility(View.VISIBLE);
            if (binding.floderRecyclerview.getHeight() != 0){
                initHeight = binding.floderRecyclerview.getHeight();
            }
            ObjectAnimator animator = ObjectAnimator.ofFloat(binding.floderRecyclerview, "translationY",
                    -initHeight, 0).setDuration(300);
            animator.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationStart(Animator animation) {
                    super.onAnimationStart(animation);
                    binding.floderRecyclerview.setVisibility(View.VISIBLE);
                }
            });
            animator.start();
            isOpenFolder = true;
        }
    }

    /**
     * 收起文件夹列表
     */
    protected void closeFolder() {
        if (isOpenFolder) {
            if (binding.floderRecyclerview.getHeight() != 0){
                initHeight = binding.floderRecyclerview.getHeight();
            }
            ObjectAnimator animator = ObjectAnimator.ofFloat(binding.floderRecyclerview, "translationY",
                    0,-initHeight).setDuration(300);
            animator.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    super.onAnimationEnd(animation);
                    binding.floderRecyclerview.setVisibility(View.GONE);
                    binding.floderMask.setVisibility(View.GONE);
                }
            });
            animator.start();
            isOpenFolder = false;
        }
    }
    @Override
    protected int getLayoutId() {
        return R.layout.activity_image_selector;
    }

    @Override
    protected Class<ImageSelectorViewModel> getViewModel() {
        return ImageSelectorViewModel.class;
    }
}
